package group.rober.dataform.handler.impl;

import group.rober.dataform.handler.DataOneHandler;
import group.rober.dataform.model.DataForm;
import group.rober.dataform.model.DataFormElement;
import group.rober.runtime.lang.MapData;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;
import java.util.Map;

/**
 * Map单条数据处理
 */
public class MapDataOneHandler extends MapDataHandler implements DataOneHandler<MapData> {


    public void initDataForm(DataForm dataForm, MapData dataObject) {

    }

    public MapData createDataObject(DataForm dataForm) {
        MapData object = new MapData();
        List<DataFormElement> elements = dataForm.getElements();
        for(DataFormElement element : elements){
            object.put(element.getCode(),null);
        }
        return object;
    }

    public MapData query(DataForm dataForm, Map<String, ?> queryParameters) {
        validateDataForm(dataForm);
        String query = dataForm.getQuery();

        RowMapper<MapData> rowMapper = getDataFormRowMapper(dataForm);
        MapData ret = mapDataAccessor.getMapDataQuery()
                .useRowMapperOnce(rowMapper)
                .selectOne(query,queryParameters);

        return ret;
    }



    public int insert(DataForm dataForm, MapData object) {
        validateDataForm(dataForm);

        MapData dbMapdata = getDbMapData(dataForm,object);
        return mapDataAccessor.getMapDataUpdater()
                .useNameConverterOnce(getNameConverter(dataForm))
                .insert(dataForm.getDataModel(),dbMapdata);
    }


    public int update(DataForm dataForm, MapData object) {
        validateDataForm(dataForm);

        String table = dataForm.getDataModel();
        MapData dbMapdata = getDbMapData(dataForm,object);
        MapData dbPkMapdata = getDbPkMapData(dataForm,object);
        return mapDataAccessor.getMapDataUpdater()
                .useNameConverterOnce(getNameConverter(dataForm))
                .update(table,dbMapdata,dbPkMapdata);
    }

    public int save(DataForm dataForm, MapData object) {
        validateDataForm(dataForm);

        String table = dataForm.getDataModel();
        MapData dbMapdata = getDbMapData(dataForm,object);
        MapData dbPkMapdata = getDbPkMapData(dataForm,object);
        return mapDataAccessor.getMapDataUpdater()
                .useNameConverterOnce(getNameConverter(dataForm))
                .save(table,dbMapdata,dbPkMapdata);
    }

    public int delete(DataForm dataForm, MapData object) {
        validateDataForm(dataForm);

        String table = dataForm.getDataModel();
        MapData dbPkMapdata = getDbPkMapData(dataForm,object);
        return mapDataAccessor.getMapDataUpdater()
                .useNameConverterOnce(getNameConverter(dataForm))
                .delete(table,dbPkMapdata);
    }
}
